<template>
  <a-modal
    :visible="visible"
    title="请选择楼宇"
    centered
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <div>
      <a-radio-group v-model:value="buildId">
        <a-radio
          :style="radioStyle"
          v-for="build of buildingList"
          :value="build.id"
          >{{ build.build_name }}</a-radio
        >
      </a-radio-group>
    </div>
  </a-modal>
</template>

<script>
import { defineComponent, ref, reactive, watch } from "vue";
import request from "../../../../common/utils/request";
import store from "../../../../store";

export default defineComponent({
  name: "ApplicationCheckBuildings",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, context) {
    const buildId = ref();
    const radioStyle = reactive({
      display: "block",
      height: "40px",
      lineHeight: "40px",
    });
    const handleCancel = () => {
      context.emit("fail");
    };
    const handleOk = () => {
      const selectedItem = buildingList.value.find(
        (item) => item.id == buildId.value
      );
      context.emit("success", {
        buildId: buildId.value,
        villageId: selectedItem.village_id,
      });
    };

    const buildingList = ref([]);
    const getBuildingList = () => {
      if (!buildingList.value.length) {
        const { checkedBuildings } = store.getters.buildingInfo;
        request.get("/org", "/build/villageAndBuildList").then((res) => {
          res.villageList.forEach((village) => {
            if (village.buildList && village.buildList.length) {
              village.buildList.forEach((build) => {
                if (checkedBuildings.includes(build.id)) {
                  buildingList.value.push(build);
                }
              });
            }
          });
          if (buildingList.value.length) {
            buildId.value = buildingList.value[0].id;
          }
        });
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          getBuildingList();
        }
      }
    );
    return {
      buildId,
      radioStyle,
      buildingList,
      handleCancel,
      handleOk,
    };
  },
});
</script>

<style></style>
